package main

import (
	"image"
	"image/color"
	"image/draw"
	"log"
	"math/rand"
	"time"

	"github.com/zserge/fenster"
)

type Fire struct {
	*image.Paletted
}

var palette = color.Palette{
	color.RGBA{0x07, 0x07, 0x07, 0xff},
	color.RGBA{0x1f, 0x07, 0x07, 0xff},
	color.RGBA{0x2f, 0x0f, 0x07, 0xff},
	color.RGBA{0x47, 0x0f, 0x07, 0xff},
	color.RGBA{0x57, 0x17, 0x07, 0xff},
	color.RGBA{0x67, 0x1f, 0x07, 0xff},
	color.RGBA{0x77, 0x1f, 0x07, 0xff},
	color.RGBA{0x8f, 0x27, 0x07, 0xff},
	color.RGBA{0x9f, 0x2f, 0x07, 0xff},
	color.RGBA{0xaf, 0x3f, 0x07, 0xff},
	color.RGBA{0xbf, 0x47, 0x07, 0xff},
	color.RGBA{0xc7, 0x47, 0x07, 0xff},
	color.RGBA{0xdf, 0x4f, 0x07, 0xff},
	color.RGBA{0xdf, 0x57, 0x07, 0xff},
	color.RGBA{0xdf, 0x57, 0x07, 0xff},
	color.RGBA{0xd7, 0x5f, 0x07, 0xff},
	color.RGBA{0xd7, 0x67, 0x0f, 0xff},
	color.RGBA{0xcf, 0x6f, 0x0f, 0xff},
	color.RGBA{0xcf, 0x77, 0x0f, 0xff},
	color.RGBA{0xcf, 0x7f, 0x0f, 0xff},
	color.RGBA{0xcf, 0x87, 0x17, 0xff},
	color.RGBA{0xc7, 0x87, 0x17, 0xff},
	color.RGBA{0xc7, 0x8f, 0x17, 0xff},
	color.RGBA{0xc7, 0x97, 0x1f, 0xff},
	color.RGBA{0xbf, 0x9f, 0x1f, 0xff},
	color.RGBA{0xbf, 0x9f, 0x1f, 0xff},
	color.RGBA{0xbf, 0xa7, 0x27, 0xff},
	color.RGBA{0xbf, 0xa7, 0x27, 0xff},
	color.RGBA{0xbf, 0xaf, 0x2f, 0xff},
	color.RGBA{0xb7, 0xaf, 0x2f, 0xff},
	color.RGBA{0xb7, 0xb7, 0x2f, 0xff},
	color.RGBA{0xb7, 0xb7, 0x37, 0xff},
	color.RGBA{0xcf, 0xcf, 0x6f, 0xff},
	color.RGBA{0xdf, 0xdf, 0x9f, 0xff},
	color.RGBA{0xef, 0xef, 0xc7, 0xff},
	color.RGBA{0xff, 0xff, 0xff, 0xff},
}

func newFire(r image.Rectangle, p color.Palette) *Fire {
	img := image.NewPaletted(r, p)
	b := r.Bounds().Max
	// seed
	for x := 0; x < b.X; x++ {
		img.SetColorIndex(x, b.Y-1, uint8(len(palette)-1))
	}
	return &Fire{Paletted: img}
}

func (f *Fire) Next() {
	b := f.Bounds().Max
	for x := 0; x < b.X; x++ {
		for y := b.Y - 1; y > 0; y-- {
			z := rand.Intn(3) - 1 // -1, 0, 1
			n := f.ColorIndexAt(x, y)
			if n > 0 && z == 0 {
				n-- // next color
			}
			f.SetColorIndex(x+z, y-1, n)
		}
	}
}

func main() {
	win, err := fenster.New(320, 200, "Doom Fire")
	if err != nil {
		log.Fatal(err)
	}
	defer win.Close()
	f := newFire(win.Bounds(), palette)
	for win.Loop(time.Second / 60) {
		if win.Key(27) || win.Key('Q') {
			break
		}
		f.Next()
		draw.Draw(win, win.Bounds(), f, image.Point{}, draw.Src)
	}
}
